﻿using System.Linq;
using System.Threading.Tasks;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Sms.V20190711;
using TencentCloud.Sms.V20190711.Models;
using Volo.Abp.DependencyInjection;
using Xms.Abp.Data.Message;

namespace Xms.Abp.Smsing.TencentCloud;

public class TencentCloudTemplateSmsSenderProvider : TemplateSmsSenderProviderBase, ITemplateSmsSenderProvider, ITransientDependency
{
    protected TencentCloudSmsSettings TencentCloudSmsSettings { get; }
    public TencentCloudTemplateSmsSenderProvider(
        SmsSettings smsSettings,
        TencentCloudSmsSettings tencentCloudSmsSettings)
        : base(smsSettings, tencentCloudSmsSettings)
    {
        TencentCloudSmsSettings = tencentCloudSmsSettings;
    }
    public override string ProviderName => "TencentCloud";

    public override async Task<SentResult<SmsSentResultItem>> SendSmsAsync(SmsMessage smsMessage)
    {
        var credential = new Credential
        {
            SecretId = TencentCloudSmsSettings.SecretId,
            SecretKey = TencentCloudSmsSettings.SecretKey
        };
        var clientProfile = new ClientProfile
        {
            HttpProfile = new HttpProfile
            {
                Endpoint = ("sms.tencentcloudapi.com")
            }
        };
        var templateCode = TencentCloudSmsSettings.SmsCodes[smsMessage.TemplateCode];
        var client = new SmsClient(credential, null, clientProfile);
        var parameters = new SendSmsRequest
        {
            PhoneNumberSet = smsMessage.PhoneNumbers.Select(r => r.Length == 11 ? "+86" + r : r).ToArray(),
            SmsSdkAppid = TencentCloudSmsSettings.SmsSdkAppId,
            Sign = TencentCloudSmsSettings.Sign,
            TemplateParamSet = smsMessage.ParameterNames.Select(s => smsMessage.TemplateParameters[s]).ToArray(),
            TemplateID = templateCode,
        };
        var response = await client.SendSms(parameters);
        var requestId = response.RequestId;
        var results = response.SendStatusSet;
        return new SentResult<SmsSentResultItem>
        {
            RequestId = requestId,
            ProviderName = ProviderName,
            Sign = TencentCloudSmsSettings.Sign,
            Items = results.Select(r =>
            new SmsSentResultItem
            {
                PhoneNumber = r.PhoneNumber,
                BizId = r.SerialNo,
                ErrorCode = r.Code,
                Message = r.Message,
                SentStatus = r.Code.ToUpper() == "OK" ? SentStatus.Sending : SentStatus.Faild,
            }),
        };
    }
}
